#include "arch/ls7a.h"
#include "arch/loongarch.h"
#include "drivers/kbd.h"
#include "drivers/atkbdmap.h"
#include "lib/stdin.h"

int alt_status = ALT_FUNCTION_OFF; 
int ctrl_status = CTRL_FUNCTION_OFF;
int shift_status = SHIFT_FUNCTION_OFF;
int caps_lock_status = CAPS_LOCK_OFF;

// 键盘中断处理
// 参考: [自制操作系统] 第17回 编写键盘驱动 - 李知行 https://www.cnblogs.com/Lizhixing/p/15956006.html
void keyboard_handler() {
    while (kbd_has_data()) {
        // u8 -> u32
        unsigned char scancode = kbd_read_byte();
        // printk("[%x ", scancode);
        unsigned int keynumber = keymap[(unsigned int)scancode];

        if (scancode == 0xF0 && kbd_has_data()) {
            // 只有特殊按键需要处理抬起时的扫描码，再读一次端口
            scancode = kbd_read_byte();
            // printk("%x ", scancode);
            keynumber = keymap[(unsigned int)scancode];

            // 处理 CTRL, SHIFT, ALT 抬起
            if (keynumber == KEY_LEFTCTRL || keynumber == KEY_RIGHTCTRL) {
                ctrl_status -= 1;
            } else if (keynumber == KEY_LEFTALT || keynumber == KEY_RIGHTALT) {
                alt_status -= 1;
            } else if (keynumber == KEY_LEFTSHIFT || keynumber == KEY_RIGHTSHIFT) {
                shift_status -= 1;
            }
        } else {
            if (keynumber == KEY_LEFTCTRL || keynumber == KEY_RIGHTCTRL) {
                // CTRL 按下
                ctrl_status += 1;
            } else if (keynumber == KEY_LEFTALT || keynumber == KEY_RIGHTALT) {
                // ALT 按下
                alt_status += 1;
            } else if (keynumber == KEY_LEFTSHIFT || keynumber == KEY_RIGHTSHIFT) {
                // SHIFT 按下
                shift_status += 1;
            } else if (keynumber == KEY_CAPSLOCK) {
                // CAPSLOCK 每次按一下状态反转
                caps_lock_status = !caps_lock_status;
            } else {
                char ch = (shift_keyboard_on())? kbd_US_shift[keynumber]: kbd_US[keynumber];
                if (ch >= 'a' && ch <= 'z' && caps_keyboard_on()) {
                    // 与 SHIFT 不同，大写锁定键只对字母区生效
                    ch += ('A' - 'a');
                } 
                // 输入内容交给输入缓冲区处理
                stdin_kbd_handler(ch, keynumber);                
            }
        }
        // printk("] key done\n");       
    } 
}
